package article

import (
	"context"
	"fmt"
	"gitee.com/bobo-rs/innovideo-services/consts"
	"gitee.com/bobo-rs/innovideo-services/framework/dao"
	"gitee.com/bobo-rs/innovideo-services/framework/model"
	"gitee.com/bobo-rs/innovideo-services/framework/model/entity"
	"gitee.com/bobo-rs/innovideo-services/library/exception"
)

// SaveArticle 保存文章数据
func (a *sArticle) SaveArticle(ctx context.Context, item entity.Article) error {
	// 保存数据
	_, err := dao.Article.Ctx(ctx).OmitEmpty().Save(item)
	if err != nil {
		return exception.New(`保存文章失败`)
	}
	return nil
}

// GetArticleList 获取文章列表
func (a *sArticle) GetArticleList(ctx context.Context, in model.ArticleGetListInput) (out *model.ArticleGetListOutput, err error) {
	out = &model.ArticleGetListOutput{}
	// 获取数据
	err = a.ArticleModel().ListAndTotal(ctx, model.CommonListAndTotalInput{
		CommonPaginationItem: in.CommonPaginationItem,
		Where:                a.ArticleWhere(in.ArticleWhereItem),
		Sort: fmt.Sprintf(
			`%s %s, %s %s`,
			dao.Article.Columns().Sort, consts.SortAsc, dao.Article.Columns().Id, consts.SortDesc,
		),
	}, &out.Rows, &out.Total)
	if err != nil {
		return nil, err
	}
	// 是否为空
	if len(out.Rows) == 0 {
		return
	}

	// 格式化数据
	for _, item := range out.Rows {
		a.FormatArticle(&item.ArticleDetailFmtItem)
	}
	return
}

// GetArticleDetail 获取文章详情
func (a *sArticle) GetArticleDetail(ctx context.Context, id uint) (detail *model.ArticleDetailItem, err error) {
	detail = &model.ArticleDetailItem{}
	// 获取文章数据
	err = a.ProcessDetailById(ctx, id, &detail)
	if err != nil {
		return nil, err
	}

	// 格式化
	a.FormatArticle(&detail.ArticleDetailFmtItem)
	return
}
